package com.conference.service.impl;

import com.conference.service.ConferenceStatisticsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class ConferenceStatisticsServiceImpl implements ConferenceStatisticsService {

    private static final Logger logger = LoggerFactory.getLogger(ConferenceStatisticsServiceImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Map<String, Object> getBasicStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        try {
            logger.debug("开始获取基础统计数据");
            
            // 获取总会议数
            Integer totalConferences = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM conference",
                Integer.class
            );
            logger.debug("总会议数: {}", totalConferences);
            
            // 获取已发布会议数
            Integer publishedConferences = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM conference WHERE status = 1",
                Integer.class
            );
            logger.debug("已发布会议数: {}", publishedConferences);
            
            // 获取即将举行的会议数（已发布且未开始的会议）
            Integer upcomingConferences = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM conference WHERE status = 1 AND start_time > ?",
                Integer.class,
                LocalDateTime.now()
            );
            logger.debug("即将举行的会议数: {}", upcomingConferences);
            
            // 获取总场地数
            Integer totalVenues = jdbcTemplate.queryForObject(
                "SELECT COUNT(DISTINCT venue_name) FROM conference_venue",
                Integer.class
            );
            logger.debug("总场地数: {}", totalVenues);

            statistics.put("totalConferences", totalConferences != null ? totalConferences : 0);
            statistics.put("publishedConferences", publishedConferences != null ? publishedConferences : 0);
            statistics.put("upcomingConferences", upcomingConferences != null ? upcomingConferences : 0);
            statistics.put("totalVenues", totalVenues != null ? totalVenues : 0);
            
            logger.debug("统计数据获取成功: {}", statistics);
        } catch (Exception e) {
            logger.error("获取统计数据时发生错误", e);
            statistics.put("totalConferences", 0);
            statistics.put("publishedConferences", 0);
            statistics.put("upcomingConferences", 0);
            statistics.put("totalVenues", 0);
        }

        return statistics;
    }

    @Override
    public Map<String, Object> getStatusDistribution() {
        Map<String, Object> distribution = new HashMap<>();
        
        try {
            logger.debug("开始获取会议状态分布数据");
            
            // 获取各状态的会议数量
            List<Map<String, Object>> results = jdbcTemplate.queryForList(
                "SELECT status, COUNT(*) as count FROM conference GROUP BY status"
            );
            
            int unpublished = 0, published = 0, ended = 0;
            for (Map<String, Object> result : results) {
                int status = ((Number) result.get("status")).intValue();
                int count = ((Number) result.get("count")).intValue();
                switch (status) {
                    case 0: unpublished = count; break;
                    case 1: published = count; break;
                    case 2: ended = count; break;
                }
            }
            
            distribution.put("unpublished", unpublished);
            distribution.put("published", published);
            distribution.put("ended", ended);
            
            logger.debug("状态分布数据获取成功: {}", distribution);
        } catch (Exception e) {
            logger.error("获取状态分布数据时发生错误", e);
        }
        
        return distribution;
    }

    @Override
    public List<Map<String, Object>> getVenueUsage() {
        try {
            logger.debug("开始获取场地使用情况数据");
            List<Map<String, Object>> results = jdbcTemplate.queryForList(
                "SELECT venue_name, COUNT(*) as usage_count " +
                "FROM conference_venue " +
                "GROUP BY venue_name " +
                "ORDER BY usage_count DESC"
            );
            logger.debug("场地使用情况数据获取成功: {}", results);
            return results;
        } catch (Exception e) {
            logger.error("获取场地使用情况数据时发生错误", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getTimeDistribution() {
        // 获取最近12个月的数据分布
        String sql = 
            "WITH RECURSIVE months AS (" +
            "  SELECT 1 as month " +
            "  UNION ALL " +
            "  SELECT month + 1 FROM months WHERE month < 12" +
            "), " +
            "conference_counts AS (" +
            "  SELECT MONTH(start_time) as month, COUNT(*) as count " +
            "  FROM conference " +
            "  WHERE start_time >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) " +
            "  GROUP BY MONTH(start_time)" +
            ") " +
            "SELECT m.month, COALESCE(cc.count, 0) as count " +
            "FROM months m " +
            "LEFT JOIN conference_counts cc ON m.month = cc.month " +
            "ORDER BY m.month";

        List<Map<String, Object>> results = jdbcTemplate.queryForList(sql);
        
        // 确保返回所有月份，即使没有会议
        List<Map<String, Object>> completeResults = new ArrayList<>();
        for (Map<String, Object> result : results) {
            Map<String, Object> monthData = new HashMap<>();
            monthData.put("month", result.get("month"));
            monthData.put("count", result.get("count"));
            completeResults.add(monthData);
        }
        
        return completeResults;
    }
} 